package com.lening.common.util;

import cn.hutool.core.util.RandomUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 赵子豪
 * @date 2024年06月12日 09时38分36秒
 */
public class FileUploadUtil {
    public static Map<String, String> upload(MultipartFile file, String filePath, String port) {
        //1.获取文件名
        String originalFilename = file.getOriginalFilename();
        if (!StringUtils.hasText(originalFilename)) {
            throw new RuntimeException("文件信息异常");
        }

        //2.获取文件后缀
        String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));

        //3.生成新的文件名
        String newFileName = RandomUtil.randomString(40) + lastName;

        //4.创建日期文件夹路径 + 文件名
        String path = LocalDate.now().format(LocalDateUtil.DATE_FORMATTER_9) + "/" + newFileName;

        //5.创建文件夹
        File f = new File(filePath + path);
        boolean mkdir = f.mkdirs();
        if (!mkdir) {
            throw new RuntimeException("文件夹创建失败");
        }

        //6.报错文件
        try {
            file.transferTo(f);
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败");
        }

        Map<String, String> result = new HashMap<>();
        result.put("originalName", originalFilename);
        result.put("name", newFileName);
        result.put("url", "http://localhost:" + port + "/img/" + path);
        return result;
    }
}